﻿Imports System.Net
Imports System.Net.Sockets

Namespace UDPSocket

    Public Class UDPBroadcastSocket

        Private Const c_BindIP As String = "0.0.0.0"
        Private Const c_BroadcastIP As String = "255.255.255.255"

        Private Sock As UdpClient
        Private mPort As Integer
        Private localEP As IPEndPoint

        Public Event OnError(ByVal ex As Exception)
        Public Event OnRecieveData(ByRef bData() As Byte, ByRef bytes As Integer)

        Public Sub New(port As Integer, Optional bindip As String = c_BindIP)

            Try

                mPort = port

                Dim ip As IPAddress = IPAddress.Parse(bindip)
                localEP = New IPEndPoint(ip, port)

                Sock = New UdpClient(localEP)

                Sock.BeginReceive(New AsyncCallback(AddressOf RecieveData), localEP)

            Catch ex As Exception
                RaiseEvent OnError(ex)
            End Try

        End Sub

        Public Sub Dispose()

            Sock.Close()
            Sock = Nothing

        End Sub

        Public ReadOnly Property IsValidSocket() As Boolean
            Get
                Return Not (Sock Is Nothing)
            End Get
        End Property

        Public Sub SendData(ByRef bData() As Byte)

            Try

                Sock.Send(bData, bData.GetLength(0), New IPEndPoint(IPAddress.Parse(c_BroadcastIP), mPort))

            Catch ex As Exception
                RaiseEvent OnError(ex)
            End Try

        End Sub

        Public Sub RecieveData(ar As System.IAsyncResult)

            Dim bytes() As Byte

            Try

                Dim EP As IPEndPoint = CType(ar.AsyncState, IPEndPoint)

                If ar.IsCompleted Then

                    bytes = Sock.EndReceive(ar, EP)

                    If Not bytes Is Nothing Then
                        Dim bytesSize As Integer = bytes.Length
                        If bytesSize > 0 Then
                            RaiseEvent OnRecieveData(bytes, bytesSize)
                        End If
                    End If
                End If

                If Not (Sock Is Nothing) Then
                    Sock.BeginReceive(New AsyncCallback(AddressOf RecieveData), CType(ar.AsyncState, IPEndPoint))
                End If

            Catch ex As Exception
                RaiseEvent OnError(ex)
            End Try

        End Sub
    End Class

End Namespace